import csv
import requests
import json
# 定义一个函数来保存数据到CSV文件
def save_to_csv(data, filename):
    with open(filename, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        for row in data:
            writer.writerow(row)
# 定义一个函数来保存数据到JSON文件
def save_to_json(data, filename):
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
import re
# 定义一个函数来解码Unicode字符
def decode_unicode(s):
    def decode_match(match):
        return chr(int(match.group(1), 16))
    return re.sub(r'\\\\u([0-9a-fA-F]{4})', decode_match, s)
# 定义一个函数来获取第一个圆括号内的内容
def get_content_in_first_parentheses(text):
    match = re.search(r'\((.*?)\)', text)
    if match:
        return match.group(1)
    else:
        return None
if __name__ == "__main__":
    url = "https://slamdunk.sports.sina.com.cn/api?p=radar&callback=jQuery1113048748717149100074_1715052227017&p=radar&s=team_standing&a=conference&_=1715052227018"
    response = requests.get(url)
    if response.status_code == 200:
        json_data = response.text
        p2 = re.compile(r'[(](.*)[)]', re.S)
        json_str = re.findall(p2, json_data).__str__()
        json_str = decode_unicode(json_str)
        print(json_str)
        save_to_csv(json_str, "team_ranking.csv")
        save_to_json(json_str, "team_ranking.json")
        print("信息保存在 team_ranking.json")
        print("信息保存在 team_ranking.json")
    else:
        print("获取失败. 错误代码:", response.status_code)
